<?php

namespace addons\hrecharge\model;

use addons\epay\library\Service;
use addons\moneylog\model\MoneyLog;
use think\Db;
use think\Model;
use Yansongda\Pay\Pay;


class Hrecharge extends Model
{

    // 表名
    protected $name = 'hrecharge';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'way_text',
        'status_text',
        'pay_time_text',
        'create_time_text'
    ];

    public function getWayList()
    {
        return ['1' => __('Way 1'), '2' => __('Way 2')];
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2')];
    }


    public function getWayTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['way']) ? $data['way'] : '');
        $list = $this->getWayList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    protected function orderNo()
    {
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    /**
     * 检验充值金额
     * @param $money
     */
    public function checkMoney($money){
        $config = get_addon_config('hrecharge');
        if($config['any_money']==0){
            $specs = array_values($config['specs']);
            if(!in_array($money,$specs)){
                $this->error="仅限提供的固定金额充值";return false;
            }
        }

    }

    /**
     * 检验充值渠道
     * @param $way
     * @return bool
     */
    public function checkWay($way){
        $config = get_addon_config('hrecharge');
        if(!in_array($way,explode(',',$config['way']))){
            $this->error = '该充值渠道未开通';
            return false;
        }
    }

    public function add($user_id,$money,$way){
        $data = [
            'order_no'  =>  $this->orderNo(),
            'user_id'   =>  $user_id,
            'money'     =>  $money,
            'way'       =>  $way
        ];
        Db::startTrans();
        try{
            $res = $this->allowField(true)->save($data);
            if($res){
                if($way==1){
                    //创建支付对象
                    $config = Service::getConfig('wechat');
                    $config['notify_url'] =request()->domain().'/addons/hrecharge/api.notify/way/wechat';
                    $pay = Pay::wechat($config);
                    $order = [
                        'out_trade_no' => $data['order_no'],
                        'total_fee' => $data['money']*100, // **单位：分**
                        'body' => '微信充值',
                    ];
                    $ret = $pay->app($order)->getContent();
                    $ret = json_decode($ret,true);
                }elseif ($way==2){
                    $config = Service::getConfig('alipay');
                    $config['notify_url'] =request()->domain().'/addons/hrecharge/api.notify/way/alipay';
                    $pay = Pay::alipay($config);
                    $order = [
                        'out_trade_no' => $data['order_no'],//你的订单号
                        'total_amount' => $data['money'],//单位元
                        'subject'      => '支付宝充值',
                    ];
                    $ret = $pay->app($order)->getContent();

                }elseif ($way==3){
                    //TO DO

                }else{
                    $this->error = "支付通道错误";
                    return false;
                }
                Db::commit();
                return ['data'=>$ret,'order_no'=>$data['order_no']];
            }else{
                $this->error = '创建订单失败';
                return false;
            }
        }catch (\Exception $e){
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }

    public function notify($order_no){
        $recharge = $this->where('order_no',$order_no)->find();
        Db::startTrans();
        try{
            MoneyLog::moneyLog($recharge['money'],$recharge['user_id'],'充值余额',2);
            $ret = $this->save(['status'=>1,'pay_time'=>time()],['id'=>$order_no]);
            return $ret;
        }catch (\Exception $e){
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }
}
